#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "sqltablemodel.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    /* 1. 建库/建表，只做一次 */
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("people.db");
    if (!db.open()) qFatal("open db error");

    db.exec("CREATE TABLE IF NOT EXISTS people ("
            "id INTEGER PRIMARY KEY AUTOINCREMENT, "
            "name TEXT, "
            "age  INTEGER)");

    /* 2. 实例化模型并注册 */
    SqlTableModel *model = new SqlTableModel(&app);

    QQmlApplicationEngine engine;
    QObject::connect(
        &engine,
        &QQmlApplicationEngine::objectCreationFailed,
        &app,
        []() { QCoreApplication::exit(-1); },
        Qt::QueuedConnection);

     // 注册后，sqlModel 可在 QML中使用
    engine.rootContext()->setContextProperty("sqlModel", model);
    engine.loadFromModule("qml_tableview_sqlite", "Main");

    return app.exec();
}
